package com.yueyang.sojourn.server.service.sojourn.order;

import com.yueyang.sojourn.server.model.enums.OrderEventTypeEnum;
import com.yueyang.sojourn.server.model.enums.OrderRefundStatusEnum;
import com.yueyang.sojourn.server.model.enums.OrderTypeEnum;
import com.yueyang.sojourn.server.model.po.SojournOrderRefund;
import com.yueyang.sojourn.server.service.sojourn.sequence.SojournSequnceManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 退款单服务
 * @author andy.yang
 * @version v1
 * @summary
 * @Copyright (c) 2019, yueyang Group All Rights Reserved.
 * @since 2020/3/29
 */
@Service
public class SojournOrderRefundService {
    @Resource
    SojournOrderRefundMapper sojournOrderRefundMapper;
    @Autowired
    SojournOrderEventService orderEventService;
    @Autowired
    SojournOrderService orderService;
    @Autowired
    SojournSequnceManager sequnceManager;

    /**
     * 创建退款单
     * @param refund
     * @return
     */
    @Transactional
    public int add(SojournOrderRefund refund){
        String sn = sequnceManager.nextValueOfOrderRefund(OrderTypeEnum.getByCode(refund.getOrderType()));
        refund.setSn(sn);
        refund.setStatus(OrderRefundStatusEnum.REFUNDED.getCode());
        //创建退款单
        int rs = sojournOrderRefundMapper.insert(refund);

        //更新订单状态
        orderService.updateRefunded(refund.getOrderId(),refund.getCreator());

        //记录事件:订单退款事件
        orderEventService.addAndReturn(refund.getOrderId(), OrderEventTypeEnum.REFUND_START,refund.getCreator());
        return rs;
    }

    /**
     * @param refundId      所属退款单id
     * @return
     * @author Andy.yang
     * @summary 退款单分页查询
     * @version v1
     * @since 2020-02-19
     */
    public SojournOrderRefund findById(Long refundId) {
        return sojournOrderRefundMapper.selectByPrimaryKey(refundId);
    }

    /**
     * 根据退款单号查询
     * @param sn      所属退款单号
     * @return
     * @author Andy.yang
     * @summary
     * @version v1
     * @since 2020-02-19
     */
    public SojournOrderRefund findByRefundSn(String sn) {
        return sojournOrderRefundMapper.findByRefundSn(sn);
    }

    /**
     * 根据订单id查询（目前一个订单只有一次退款）
     * @param orderId     所属订单id
     * @return
     * @author Andy.yang
     * @summary
     * @version v1
     * @since 2020-02-19
     */
    public SojournOrderRefund findByOrderId(Long orderId) {
        return sojournOrderRefundMapper.findByOrderId(orderId);
    }
}
